﻿/*-----------------------------------------------
// File: ManagerController.cs
// Description: 
// Author: Shaobing	492057342@qq.com
-----------------------------------------------*/
using UnityEngine;
using System.Collections;
using Room;
using UnityEngine.SceneManagement;
using System.Collections.Generic;
using ProtoBuf.Message;
using AssetLoad;

public class ManagerController : MonoBehaviour
{
    public Battle.BattleManager battleManager;
    public UI.PageManager pageManager;
    public FormationResourceCache formationResourceCache;
    public Story.StoryManager storyManager;
    public RoomModelPool roomModelPool;
    public GuideManager guideManager;
    public LoadingKit loadingKit;
    public CGKit cgKit;
    //public AssetUpdateShow assetUpdateShow;

    public UIRoot uiroot;
    public SceneType CurrentSceneType
    {
        get
        {
            return Room.RoomManager.curSceneType;
        }
    }
    private int beforeBattleLevel;
    public CameraTool cameraTool;

    public void RoomToBattleRecruit()
    {
        LoadingPanel.Instance.ShowMask(0.5f);
        StartCoroutine(_RoomToBattleRecruit());
    }

    IEnumerator _RoomToBattleRecruit()
    {
        yield return new WaitForSeconds(0.5f);
        pageManager.ChangeToBattle();
        Room.RoomManager.Switch(SceneType.BATTLE);
        battleManager.gameObject.SetActive(true);
        battleManager.Init();
        battleManager.NewFight();
        cameraTool.SwitchBattleCamera();
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
    }

    public void BattleRecruitToRoom()
    {
        battleManager.Unload();
        Time.timeScale = 1f;
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        EasyTouchTool.Instance.Hide();
        StartCoroutine(_BattleRecruitToRoom());
    }

    IEnumerator _BattleRecruitToRoom()
    {
        LoadingPanel.Instance.ShowMask(0.5f);
        yield return new WaitForSeconds(0.5f);
        LoadingPanel.Instance.HideLoading();
        cameraTool.SwitchSceneCamera();
        pageManager.ChangeUIBack();
        yield return null;
    }

    public void RushToBattle() {
        pageManager.ChangeToBattle();
        Room.RoomManager.Switch(SceneType.BATTLE);
        battleManager.gameObject.SetActive(true);
        battleManager.Init();
        battleManager.NewFight();
        cameraTool.SwitchBattleCamera();
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
    }

    public void BattleToRush() {
        battleManager.Unload();
        Time.timeScale = 1;
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        EasyTouchTool.Instance.Hide();
        StartCoroutine(_BattleToRush());
    }

    IEnumerator _BattleToRush() {
        LoadingPanel.Instance.ShowMask(0.5f);
        yield return new WaitForSeconds(0.5f); 
        cameraTool.SwitchSceneCamera();
        pageManager.ChangeUIBack();
        Room.RoomManager.Switch(SceneType.RUSH);
        StaticData.isMazeTraderNeedShow = true;
    }

    public void RoomToBattle(int preLevel=0)
    {
        if(preLevel!=0)
        {
            beforeBattleLevel = preLevel;
        }
        else
        {
            beforeBattleLevel = StaticData.playerData.level;
        }
        
        LoadingPanel.Instance.ShowLoading();
        beforeBattleLevel = StaticData.playerData.level;
        pageManager.ChangeToBattle();
        Room.RoomManager.Switch(SceneType.BATTLE);
        _RoomToBattle();
        pageManager.HideUI();
        UIAutoSize.Instance.ShowMaskUI(true);
    }
    void _RoomToBattle()
    {
        battleManager.gameObject.SetActive(true);
        battleManager.Init();
        battleManager.NewFight();
        UIAutoSize.Instance.ShowMaskUI(true);
        cameraTool.SwitchBattleCamera();
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
    }

    public void BattleToRoomScene()
    {
        LoadingPanel.Instance.ShowLoading();
        battleManager.Unload();
        Time.timeScale = 1;
        // Room.RoomManager.Switch(SceneType.TOWN);
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        //roomManager.BattleToRoom();
        EasyTouchTool.Instance.Hide();
        cameraTool.SwitchSceneCamera();
        pageManager.ChangeUIBack();

        if (beforeBattleLevel != StaticData.playerData.level)
        {
            BoxManager.CreateLevelUp(beforeBattleLevel, StaticData.playerData.level);
        }
    }

    public void BattleToRoom()
    {
        LoadingPanel.Instance.ShowLoading();
        enterBattle = false;
        battleManager.Unload();
        Time.timeScale = 1;
        _BattleToRoom();
    }
    void _BattleToRoom()
    {
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        //roomManager.BattleToRoom();
        EasyTouchTool.Instance.Hide();
        cameraTool.SwitchSceneCamera();
        pageManager.ChangeUIBack();

        LoadingPanel.Instance.HideLoading();
        if (beforeBattleLevel != StaticData.playerData.level)
        {
            BoxManager.CreateLevelUp(beforeBattleLevel, StaticData.playerData.level);
        }
    }

    public void RoomToRush() {
        LoadingPanel.Instance.ShowLoading();
        RoomManager.Switch(SceneType.RUSH);
    }


    //public void ActivityToBattle()
    //{
    //    LoadingPanel.Instance.ShowLoading();
    //    beforeBattleLevel = StaticData.playerData.level;
    //    pageManager.ChangeToBattle();
    //    RoomManager.Switch(SceneType.BATTLE);
    //    _RoomToBattle();
    //}

    //public void BattleToActivity()
    //{
    //    LoadingPanel.Instance.ShowLoading();
    //    battleManager.Unload();
    //    Time.timeScale = 1;
    //    _BattleToRoom();
    //}


    public void CopyToBattle()
    {
        //LoadingPanel.Instance.ShowLoading();
        EasyTouchTool.Instance.Hide();
        beforeBattleLevel = StaticData.playerData.level;
        //StartCoroutine(WaitCopyEffectOver());
        var runMap = pageManager.currentPage as UI.UICopyRunMap;
        runMap.PlayIntoBattleEffect();
        LoadingPanel.Instance.ShowMask(0.5f);
        enterBattle = true;
        receivePveMsg = false;
        Copy.CopyManager.Instance.CopyToBattleScene(_CopyToBattle);
        StartCoroutine(WaitCopyBattleLoad());

    }
    private bool enterBattle = false;
    private bool receivePveMsg = false;
    IEnumerator WaitCopyEffectOver()
    {
        var runMap = pageManager.currentPage as UI.UICopyRunMap;
        runMap.PlayIntoBattleEffect();
        LoadingPanel.Instance.ShowMask(0.5f);
        EasyTouchTool.Instance.Hide();
        //var copyRoom = Room.RoomManager.GetRoom(SceneType.COPY) as Room.RoomCopy;
        //yield return new WaitForSeconds(1f);
        //AssetLoad.AssetBundleManager.Instance.LoadAssetBundle("UI_DXP/UI_jinruzhandou");
        //while (!AssetLoad.AssetBundleManager.Instance.IsLoadedAssetBundle("UI_DXP/UI_jinruzhandou"))
        //{
        //    yield return 1;
        //}
        //Object effObj = AssetLoad.AssetBundleManager.Instance.GetAssetFromBundle("UI_DXP/UI_jinruzhandou", "UI_jinruzhandou", typeof(GameObject));
        //GameObject effGobj = Instantiate(effObj) as GameObject;
        //effGobj.transform.parent = GameObject.Find("/UI Root").transform;
        //effGobj.transform.localScale = Vector3.one;
        //effGobj.transform.position = Vector3.zero;
        //effGobj.name = "UI_jinruzhandou";
        enterBattle = true;
        Copy.CopyManager.Instance.CopyToBattleScene(_CopyToBattle);
        
        yield return new WaitForSeconds(0.5f);
        if (!enterBattle)
        {
            yield break;
        }
        Room.RoomManager.Switch(SceneType.BATTLE);
        cameraTool.SwitchBattleCamera();
        runMap.EndIntoBattleEffect();
        pageManager.ChangeToBattle();

        //yield return new WaitForSeconds(1f);


    }

    void _CopyToBattle()
    {
        receivePveMsg = true;
        //battleManager.gameObject.SetActive(true);
        //battleManager.Init();
        //Room.RoomManager.Switch(SceneType.BATTLE);
        //battleManager.NewFight();

    }

    private IEnumerator WaitCopyBattleLoad()
    {
        yield return new WaitForSeconds(0.5f);
        while (true)
        {
            if(!enterBattle)
            {
                yield break;
            }
            else if(receivePveMsg)
            {
                var runMap = pageManager.currentPage as UI.UICopyRunMap;
                Room.RoomManager.Switch(SceneType.BATTLE);
                cameraTool.SwitchBattleCamera();
                runMap.EndIntoBattleEffect();
                pageManager.ChangeToBattle();
                Room.RoomManager.Switch(SceneType.BATTLE);
                battleManager.gameObject.SetActive(true);
                battleManager.Init();
                battleManager.NewFight();
                yield break;
            }
            else
            {
                yield return 1;
            }
        }
    }

    public void CopyBattleLoadComplete()
    {
        //GameObject obj = GameObject.Find("/UI Root/UI_jinruzhandou");
        //Destroy(obj);
        //LoadingPanel.Instance.gameObject.SetActive(true);
        LoadingPanel.Instance.HideMask(0.5f);
    }


    public void BattleToCopy()
    {
        Time.timeScale = 1;
        //if(!StaticData.isCompleteTask)
        //{
        //LoadingPanel.Instance.gameObject.SetActive(true);
        LoadingPanel.Instance.ShowMask();
        //}
        battleManager.Unload();

        string deadMonsterId = null;
        if (StaticData.isLastBattleWin)
        {
            deadMonsterId = StaticData.currFightTaskId;
        }
        else
        {

        }

        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        Room.RoomManager.Switch(SceneType.COPY, deadMonsterId);
        pageManager.ChangeUIBack();

    }



    public void LoginToUI()
    {
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        storyManager.OnLogin();
        //if (guideManager != null)
        //    guideManager.gameObject.SetActive(true);
        StaticData.townNeedLogin = true;
        pageManager.ShowUI();
        pageManager.OpenPage("TownPage", "");

    }
    

    public void LoginToBattle()
    {
        StartCoroutine(_LoginToBattle());
    }

    IEnumerator _LoginToBattle()
    {
        LoadingPanel.Instance.ShowLoading();
        yield return 1;
        Debug.Log("[Managercontroller] LoginToBattle.");
        StaticData.InitTableData();
        yield return 0;
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        // 初始化战斗数据
        LoadingPanel.Instance.SetTipWord(TableTextBlo.GetText("first_battle_tip"));
        //string tip = TableTextBlo.GetText("first_battle_tip");
        //LoadingPanel.Instance.ShowLoading(tip, true, 10);
        StaticData.curBattleData.SetBootFightData();
        //StaticData.curBattleData.SetTestData(BattleType.FIRST);
        battleManager.Init();
        Room.RoomManager.Switch(SceneType.BATTLE);
        battleManager.NewFight();
        cameraTool.SwitchBattleCamera();
    }

    public void BattleToLogin()
    {
        battleManager.Unload();
        ToLogin();
        cameraTool.SwitchSceneCamera();
    }

    public void ToLogin()
    {
        LoadingPanel.Instance.HideLoading();
        GameObject loginObj = GameObject.Find("/UI Root/loginUI");
        if (loginObj != null)
        {
            Destroy(loginObj);
        }
        loginObj = Instantiate(Resources.Load("Pages/loginUI")) as GameObject;
        loginObj.name = "loginUI";
        GameObject uiroot = GameObject.Find("/UI Root");
        loginObj.transform.parent = uiroot.transform;
        loginObj.transform.localScale = Vector3.one;
        loginObj.transform.localPosition = Vector3.zero;

    }

    public void DestoryCGKit()
    {
        if (cgKit != null)
        {
            cgKit.Close();
        }
    }



    public static ManagerController Instance
    {
        get { return instance; }
    }
    private static ManagerController instance;
    void Awake()
    {
        instance = this;
    }

    public void BackToLogin()
    {
        StaticData.isLogining = false;
        Debug.Log("back to login " + Time.frameCount);
        BoxManager.ClearSocketBox();
        BoxManager.CreateNetMask();
        GameObject loginObj = GameObject.Find("/UI Root/loginUI");
        if (loginObj != null)
        {
            Destroy(loginObj);
        }
        BoxManager.CleanAllBox();
        NetAPI.Disconnect();

        NetAPI.CloseSocket();
        NetAPI.CloseHttp();
        DataMessageTool.CleanAllHandler();
        if(Room.RoomManager.currentRoom != null && Room.RoomManager.currentRoom.charactorManager  != null)
        {
            Room.RoomManager.currentRoom.charactorManager.ClearAll();
        }

        TimingTaskManager.Instance.Clear();
        Room.RoomManager.Switch(SceneType.LOGIN);
        AudioManager.Instance.Clear();
        formationResourceCache.Clear();
        storyManager.Clear();
        pageManager.Clear();
        roomModelPool.Clear();
        Battle.BattleManager.Instance.Clear();

        StaticData.ClearAllData();
        GameObjectPoolManager.Instance.ClearAll();
        guideManager.Clear();
        AssetLoad.ResourceManager.Instance.Clear();
        AssetLoad.AssetBundleManager.Instance.Clear();
        AssetLoad.AssetBundleManager.Instance.Initialize();
        LoadingPanel.Instance.HideLoading();
        cameraTool.SwitchSceneCamera();
        loginObj = Instantiate(Resources.Load("Pages/loginUI")) as GameObject;
        loginObj.name = "loginUI";
        GameObject uiroot = GameObject.Find("/UI Root");
        loginObj.transform.parent = uiroot.transform;
        loginObj.transform.localScale = Vector3.one;
        loginObj.transform.localPosition = Vector3.zero;

        //assetUpdateShow.Hide();
        System.GC.Collect();

        StaticData.isRelogin = true;
        BoxManager.forceNeedRelogin = false;

    }

    public void TownToRaid()
    {
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        LoadingPanel.Instance.ShowLoading();

        Room.RoomManager.Switch(SceneType.RAID);
        Room.RoomManager.currentRoom.Foreground();
    }

    public void RaidToTown()
    {
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        LoadingPanel.Instance.ShowLoading();
        
        if (Room.RoomManager.curSceneType ==  SceneType.RAID)
        {
            Room.RoomManager.Switch(SceneType.TOWN);
            Room.RoomManager.currentRoom.Foreground();
        }
        else
        {
            Room.RoomManager.Switch(SceneType.TOWN);
            Room.RoomManager.currentRoom.Foreground();
        }
    }


    public void TownToField()
    {
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        var type = Room.RoomManager.curSceneType;

        switch (type)
        {
            case SceneType.TOWN:
                LoadingPanel.Instance.ShowLoading();
                Room.RoomManager.Switch(SceneType.FIELD);
                Room.RoomManager.currentRoom.Foreground();
                break;
            case SceneType.FIELD:
                LoadingPanel.Instance.ShowLoading();
                Room.RoomManager.Switch(SceneType.FIELD);
                Room.RoomManager.currentRoom.Foreground();
                break;
            default:
                LoadingPanel.Instance.ShowLoading();
                Room.RoomManager.Switch(SceneType.FIELD);
                Room.RoomManager.currentRoom.Foreground();
                break;
        }
        
    }

    public void _CompleteTownToField()
    {
        LoadingPanel.Instance.HideLoading();
        EasyTouchTool.Instance.ShowJoystick();
    }

    public void FieldToTown()
    {
        Debug.Log("field to town begin " + Time.unscaledTime * 1000);
        
        LoadingPanel.Instance.ShowLoading();
        Room.RoomManager.Switch(SceneType.TOWN);
        Room.RoomManager.currentRoom.Foreground();
         
        UI.UIFieldRunMap.fieldId = "";
    }

    public void LoginToField(string loginName)
    {
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        storyManager.OnLogin();
        StaticData.townNeedLogin = true;

        var str = loginName.Substring(ServerScene.Field.Length);
        var sss = str.Split(new char[1] { '#' }, System.StringSplitOptions.RemoveEmptyEntries);
        StaticData.fieldId = sss[0];

        
        var sceneName = Dict.Blo.DictFieldBlo.GetOne(sss[0]).FieldMap;
        if (AssetBundleManager.Instance.IsAssetExist("map/" + sceneName))
        {
            pageManager.OpenPage("UIFieldRunMap", "");
        }
        else
        {
            StaticData.fieldId = "";
            TrySceneTransfer(ServerScene.Town, Vector3.zero, "TownPage");
        }
    }
    

    public void FieldToBattle()
    {
        RoomToBattle();
    }
    public void BattleToField()
    {
        LoadingPanel.Instance.ShowLoading();
        battleManager.Unload();
        pageManager.ShowUI();
        Room.RoomManager.Switch(SceneType.FIELD);
        Room.RoomManager.currentRoom.Foreground();
    }

    public GameObject ShowEnterGameStory()
    {
        uiroot.gameObject.SetActive(false);
        var story = GameObject.Instantiate(Resources.Load<GameObject>("Story2d/EnterGameStory"));
        story.transform.localPosition = Vector3.zero;
        story.transform.localEulerAngles = Vector3.zero;
        story.GetComponent<Story2dEnterGame>().Play();
        return story;
    }

    public void EnterGameStoryDone(GameObject story)
    {
        uiroot.gameObject.SetActive(true);
        GameObject.Destroy(story);
    }

    public void LoginToUnion()
    {
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        storyManager.OnLogin();
        StaticData.townNeedLogin = true;
        pageManager.ShowUI();
        pageManager.OpenPage("UIUnionRunMap", "");
    }

    public void TownToUnion()
    {
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        
        if (Room.RoomManager.curSceneType != SceneType.UNION)
        {
            LoadingPanel.Instance.ShowLoading();
            Room.RoomManager.Switch(SceneType.UNION);
        }
       
        Room.RoomManager.currentRoom.Foreground();
    }

    public void _CompleteTownToUnion()
    {
        LoadingPanel.Instance.HideLoading();
        EasyTouchTool.Instance.ShowJoystick();
    }

    public void UnionToTown()
    {
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        LoadingPanel.Instance.ShowLoading();
        Room.RoomManager.Switch(SceneType.TOWN);
        Room.RoomManager.currentRoom.Foreground();
    }

    /// <summary>
    /// 登录往公会战传送
    /// </summary>
    public void LoginToUnionFight()
    {
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        storyManager.OnLogin();
        StaticData.townNeedLogin = true;
        pageManager.ShowUI();
        pageManager.OpenPage("UIUnionFightRunMap", "");
    }

    /// <summary>
    /// 从公会场景往公会战场传
    /// </summary>
    public void UnionToUnionFight()
    {
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        LoadingPanel.Instance.ShowLoading();
        Room.RoomManager.Switch(SceneType.UNIONFIGHT);
        Room.RoomManager.currentRoom.Foreground();
    }

    /// <summary>
    /// 从城镇往公会战场传送
    /// </summary>
    public void TownToUnionFight()
    {
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        LoadingPanel.Instance.ShowLoading();
        Room.RoomManager.Switch(SceneType.UNIONFIGHT);
        Room.RoomManager.currentRoom.Foreground();
    }

    /// <summary>
    /// 公会战场返回城镇
    /// </summary>
    public void UnionFightToTown()
    {
        AssetLoad.ResourceManager.Instance.UnloadUnusedResources();
        LoadingPanel.Instance.ShowLoading();
        Room.RoomManager.Switch(SceneType.TOWN);
        Room.RoomManager.currentRoom.Foreground();
    }


    /// <summary>
    /// 公会战场返回公会
    /// </summary>
    public void UnionFightToUnion()
    {

    }
    

    #region 场景转换
    public string willOpenPage = "";
    public string willTransferScene = "";
    public System.Action callback;
    public bool registCb = false;
    void RegistSceneTransfer()
    {
        NetAPI.RegistSocketHandler(OpDefine.SCTransferScene, SceneTransferCallback);
        registCb = true;
    }
    void UnregistSceneTransfer()
    {
        NetAPI.UnregisterSocketHandler(OpDefine.SCTransferScene, SceneTransferCallback);
        registCb = false;
    }
    
    public void TrySceneTransfer(string nextScene, Vector3 pos, string willOpenPage = "", System.Action tranCallback = null)
    {
        if (!registCb)
        {
            RegistSceneTransfer();
        }
        
        this.willOpenPage = willOpenPage;
        this.callback = tranCallback;
        this.willTransferScene = nextScene;
        var msg = new CSTransferScene();
        msg.target = nextScene;
        msg.point = new PointNew();
        msg.point.x = pos.x;
        msg.point.y = pos.y;
        msg.point.z = pos.z;
        NetAPI.SendSocket(OpDefine.CSTransferScene, msg);
    }

    public void SceneTransferCallback(object obj)
    {
        var msg = (SCTransferScene)obj;
        if (msg.result == BOOL.TRUE)
        {
            if (callback != null)
                callback();
            if (!string.IsNullOrEmpty(willOpenPage))
                pageManager.OpenPage(willOpenPage, "");
        }
        else
        {
            //BoxManager.CreatePopupTextBox("scene transfer faid");
            Debug.LogError("Scene Transfer Faid "+"["+ willTransferScene+"]");
        }

        if(registCb)
        {
            UnregistSceneTransfer();
        }
    }
    #endregion
}
